<template>
	<!-- 新建日常报销单 -->
	<view class="container"
		style="width: 100%;box-sizing: border-box;background-color: #fff;padding:20rpx 20rpx 20rpx 20rpx">
		<uni-forms ref="form" :modelValue="entity" label-width="100px">
			<view>
				<view>
					<uni-section title="基本信息:" type="line"></uni-section>
				</view>
				<uni-forms-item label="申请日期:" :rules="$rules.handle.ApplicationDate" required name="ApplicationDate">
					<view @click="timeClick('ApplicationDate')">
						<uni-easyinput v-model="entity.ApplicationDate" :disabled="disabled" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="公司名称:" :rules="$rules.handle.CompanyName" required name="CompanyName">
					<view @click="CustomerChoice('CompanyName')">
						<uni-easyinput v-model="entity.CompanyName" suffixIcon="compose" :disabled="disabled" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="部门名称:" :rules="$rules.handle.DeptName" required name="DeptName">
					<view @click="CustomerChoice('DeptName')">
						<uni-easyinput v-model="entity.DeptName" suffixIcon="compose" :disabled="disabledDeptName" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="报销人姓名:" :rules="$rules.handle.ApplicationPerson" required
					name="ApplicationPerson">
					<view>
						<uni-easyinput v-model="entity.ApplicationPerson" :disabled="disabled" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="报销单号:" name="ReimburseCode">
					<view>
						<uni-easyinput v-model="entity.ReimburseCode" :disabled="true" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="票面总金额:" name="FaceAmount">
					<view>
						<uni-easyinput v-model="entity.FaceAmount" :disabled="true" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="报销总金额:" name="ReimburseAmount">
					<view>
						<uni-easyinput v-model="entity.ReimburseAmount" :disabled="true" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="备注:">
					<view>
						<uni-easyinput v-model="entity.Abstract" type="textarea" maxlength="300" :disabled="disabled" />
					</view>
				</uni-forms-item>


			</view>
			<view class="flex Acenter Jbetween">
				<uni-section title="费用明细" type="line"></uni-section>
				<view class="flex Acenter Jbetween" @click="AddDetailClick">
					<u-icon name="plus-circle-fill" color="#2979ff" size="45"></u-icon>
					<text style="color:#2979ff;font-weight:bold;padding-left: 10rpx;">添加明细</text>

				</view>
			</view>
			<view class="scrollBox">
				<scroll-view style="width: 100%;height: 100%;" scroll-y="true">
					<view style="padding-bottom: 50px;">
						<!-- 这里是产品明细明细明细明细明细明细明细明细明细明细明细明细明细明细明细
						明细明细明细明细明细明细明细明细明细明细明细明细明细
						明细明细明细明细明细明细明细明细明细明细明细 -->
						<view class=" " v-for="(item, index) in detailData" :key="item.Id" style=" width: 93%;
					      margin: 0 auto;
					      box-shadow: 3px 4px 16px 0px #6b6b6a;
					      margin-top: 40rpx;
					      margin-bottom: 10px;
					      background-color: #ffffff;
					      border-radius: 10rpx;
					     padding: 20rpx;
					    ">
							<view class="left" style="font-size: 14px; color: #000">
								<span class="bold">客户: {{item.CustomerName}}</span>
							</view>
							<view class="flex Jbetween" style="font-size: 14px">
								<span class="font">业务性质: {{ item.ExpenseType || "无" }}</span>
								<span class="font">票据类型: {{ item.BillTypeName || "无" }}</span>
							</view>
							<view class="flex Jbetween" style="font-size: 14px">
								<span class="font">发票分类: {{ item.InvoiceClassificationName || "无" }}</span>
								<span class="font">是否无票支出: {{ item.IsBill? item.IsBill ==1 ? '是' : "否" : "否"}}</span>
							</view>
							<view class="flex Jbetween" style="font-size: 14px">
								<span class="font">票面金额: {{ item.FaceAmount || "无" }}</span>
								<span class="font">报销金额: {{ item.ReimburseAmount || "无" }}</span>
							</view>
							<view class="flex Jbetween" style="font-size: 14px">
								<span class="font">票据张数: {{ item.BillsNum +"张" }}</span>
								<span class="font">摘要: {{ item.ItemAbstract || "无" }}</span>
							</view>
							<view class="flex Jbetween" style="font-size: 14px">
								<span v-if="item.reimburse_Files" class="font">附件 *
									{{item.reimburse_Files.length}}</span>
							</view>
							<view class="flex Jend">
								<view @click.stop="handleItemEdit(entity, item, index)" style="
								  width: 15%;
								  border-radius: 5px;
								  line-height: 30px;
								  color: #fff;
								  text-align: center;
								  margin-top: 10rpx;
								  background-color: #2979ff;
								  margin-right: 30rpx;
								">
									修改
								</view>
								<view @click="detailDataDelete([item.Id], index)" style="
					          width: 15%;
					          border-radius: 5px;
					          line-height: 30px;
					          color: #fff;
					          text-align: center;
					          background-color: red;
					        ">
									删除
								</view>
							</view>
						</view>
						<view style="margin: 50rpx 0;">
							<u-empty v-if="detailData.length==0" text="请添加明细" mode="list"></u-empty>
						</view>
					</view>
				</scroll-view>
			</view>
			<view v-if="disabled">
				<view class="submitButton" style="display: flex;align-items: center;">
					<u-button type="default" plain style="font-size: 14px;width: 200rpx;" @click="urlBack"
						:loading="loading">返回</u-button>
					<u-button type="primary" style="font-size: 14px;width: 200rpx;" @click="onSubmit(2)"
						:loading="loading">审批</u-button>
				</view>
			</view>
			<view v-else>
				<view class="submitButton" style="display: flex;align-items: center;">
					<u-button type="primary" plain style="font-size: 14px;width: 200rpx;" @click="onSubmit(0)"
						:loading="loading">保存草稿</u-button>
					<u-button type="primary" style="font-size: 14px;width: 200rpx;" @click="onSubmit(1)"
						:disabled="isButtonDisabled" :loading="loading">提交</u-button>
				</view>
			</view>
		</uni-forms>

		<!-- 选择日期 -->
		<u-calendar v-model="isCalendar" :mode="mode" placeholder="请选择日期" @change="timeChangeClick"></u-calendar>
		<!-- 引用公司子组件 -->
		<Company ref="Company" @change="changeHandler" @cancel="$refs.Company.close()" :title="title"></Company>
	</view>
</template>

<script>
	import {
		mapState
	} from "vuex";
	// 引用公司选择子组件
	import Company from '@/components/Company.vue'
	import AddDetail from './AddDetail.vue';
	// 引入公共头部组件
	import {
		//获取公司列表数据
		CompanyDataList,
		// 获取部门下拉列表
		DepartmentList,
		// 日常新建保存草稿 提交
		Reimburse_Daily_MainSaveData,
		// 判断姓名是否存在人员档案中
		Base_UserGetExistEmployee
	} from "@/api/interface.js";
	export default {
		components: {
			// 公司组件
			Company,
			// 新建明细
			AddDetail,

		},
		data() {
			return {
				// 是否允许提交按钮
				isButtonDisabled: false,
				// 公司和部门弹窗的标题
				title: "请选择公司",
				// 禁用
				disabled: false,
				// 禁用部门名称
				disabledDeptName: false,
				// 加载
				loading: false,
				entity: {
					DeptName: ""
				},
				// 是否显示日期弹窗
				isCalendar: false,
				// 日期选择
				mode: 'date',
				// 是否展示公司选择底部弹窗组件
				showPopup: false,
				// 底部弹窗列表数据
				columns: [],
				// 点击弹出底部弹窗的字段类型
				dataType: "",
				// 明细表
				detailData: [],
				// 日常报销单明细
				DailyFormChildrenList: [],
				// 差旅报销单明细
				TravleFormChildrenList: [],
				options: {},
				// 附件列表
				reimburse_Files: [],
				Upload: []
			}
		},
		computed: {
			...mapState(["UserInfo", "BillTypeOptions", "ExpenseTypeOptions", "InvoiceClassificationOptions",
				"CompayListOptions"
			]),
		},
		onShow() {
			//默认赋值当前选择日期
			let time = this.$moment().format("YYYY-MM-DD");
			this.entity.ApplicationDate = time
		},
		onUnload() {},

		onLoad(options) {
			this.options = options
			// 公司名称
			let CompanyName = this.CompayListOptions.filter(item => item.value === this.UserInfo.UserInfo.CompanyId)[0]
				.text
			// 公司id
			let CompanyId = this.CompayListOptions.filter(item => item.value === this.UserInfo.UserInfo.CompanyId)[0]
				.value
			// 默认取当前用户公司名称和id
			this.$set(this.entity, 'CompanyName', CompanyName)
			this.$set(this.entity, 'CompanyId', CompanyId)
			// 报销人姓名默认赋值
			this.$set(this.entity, 'ApplicationPerson', this.UserInfo.UserInfo.StaffName)
			if (this.entity.CompanyId) {
				// 默认取当前公司id下的部门名称和id
				// 获取部门下拉列表
				this.getDepartmentList('默认', CompanyId)
			}
		},
		methods: {
			// 求和函数
			sumObjects(arr, key) {
				return arr.reduce((sum, current) => sum + parseFloat(current[key] || 0), 0)
			},
			// 计算票面总金额和报销总金额
			getTotalAmount() {
				// 计算票面总金额
				const newFaceAmount = this.sumObjects(this.detailData, 'FaceAmount')
				// 计算报销总金额
				const newReimburseAmount = this.sumObjects(this.detailData, 'ReimburseAmount')
				// 计算差额
				const totalDifference = newFaceAmount - newReimburseAmount

				// 票面总金额和报销总金额赋值entity
				this.entity.FaceAmount = newFaceAmount
				this.entity.ReimburseAmount = newReimburseAmount
				// 差额赋值
				this.entity.Difference = totalDifference
				// 应付金额赋值
				this.entity.PayableAmount = newReimburseAmount
				// 应付金额赋值后实时更新大写
				const value = this.$utils.transformToUppercase(this.entity.PayableAmount)
				// 大写赋值
				this.entity.Capitalization = value
				console.log('计算票面总金额和报销总金额了', this.entity, this.detailData, newFaceAmount, newReimburseAmount)
			},
			// 日期时间选择
			timeClick(type) {
				// if (this.disabled) return
				this.isCalendar = true
			},
			// 日期选择calendarChange
			timeChangeClick(event) {
				console.log('事件选择', event)
				// *************注意  存储必须用set赋值  否则校验不通过   ************************************
				this.$set(this.entity, "ApplicationDate", event.result);
				// *************注意  存储必须用set赋值  否则校验不通过   ************************************
			},
			// 返回
			urlBack() {
				uni.navigateBack()
			},
			// 编辑条件修改子表
			setDetailData(type, data) {
				console.log('监听过来日常子表开始添加了', type, data, this.detailData)
				if (type === 'add') {
					// 新增
					this.detailData.push(data)
				} else {
					if (typeof(data.ExpenseTypeName) === 'object') {
						data.ExpenseTypeName = data.ExpenseTypeName.map(item => {
							return item.text
						}).join('/')
					}
					// 编辑
					let newDetailData = this.detailData
					newDetailData.forEach((item, index) => {
						if (item.Id && item.Id === data.Id) {
							newDetailData[index] = data
							console.log('合并后的-resultresult---------resultresult-', item, data)
						} else {
							// 替换数组里对应对象
							this.detailData.splice(this.detailDataIndex, 1, data)
						}
					})
				}
				// 计算票面总金额和报销总金额
				this.getTotalAmount(data)
				this.$forceUpdate()
				console.log('改完后的------------------------------', data, this.detailData)
			},
			// 子表编辑
			handleItemEdit(entity, item, index) {
				this.detailDataIndex = index
				let data = {
					entity: entity,
					item: item
				}

				console.log('剪辑了', entity)
				uni.navigateTo({
					url: "/pages/Approval/EditDetail?data=" + JSON.stringify(data)
				})

			},
			// 添加明细
			AddDetailClick() {
				console.log('添加名i')
				uni.navigateTo({
					url: "/pages/Approval/AddDetail"
				})
				// this.$refs.AddDetail.openForm()
			},
			// 子表删除
			detailDataDelete(event, index) {
				this.detailData.splice(index, 1)
				// 重新计算总金额
				this.getTotalAmount()
			},
			// 公司选择
			CustomerChoice(value) { // 获取公司下拉列表数据
				this.dataType = ""
				this.dataType = value
				console.log('公司还是部门', value, this.entity)
				// 判断公司名称是否为空  再点击部门选择的时候
				if (value === 'DeptName') {
					if (!this.entity.CompanyName) {
						// 如果没有公司先禁用部门名称
						this.disabledDeptName = true
						this.$errorToast('请先选择公司')
						return
					}
				}
				if (value === 'CompanyName') {
					// 获取公司下拉列表数据
					this.getCompanyDataList()
				} else {
					console.log('打开部门弹窗了', this.entity, )
					this.title = "请选择部门"
					if (this.entity.CompanyId) {
						// 获取部门下拉列表
						this.getDepartmentList('选择', this.entity.CompanyId)
					}
				}


			},
			// 获取部门列表数据
			// 底部弹窗选中事件
			changeHandler(children) {
				if (children) {
					// 如果选择公司了.打开部门名称
					this.disabledDeptName = false
				}
				// 公司和部门名称id赋值
				if (this.dataType === 'CompanyName') {
					// 重新选择公司名称  初始化部门名称和id
					this.entity.DeptName = ""
					this.entity.DepartmentId = ""
					this.$set(this.entity, "CompanyName", children.label);
					this.$set(this.entity, "CompanyId", children.value);
				} else {
					this.$set(this.entity, "DeptName", children.label);
					this.$set(this.entity, "DepartmentId", children.value);
				}

				this.$forceUpdate()
				// 隐藏底部弹窗
				this.$refs.Company.close()
				console.log('选中了', children, this.entity)
			},
			//获取公司列表数据
			getCompanyDataList() {
				CompanyDataList({}).then(resJson => {
					if (resJson.Success) {
						this.columns = resJson.Data.map(item => {
							return {
								value: item.Id,
								label: item.title
							}
						})

					}
					this.$refs.Company.open(this.columns)
					console.log('获取公司列表数据', this.columns)
				})
			},
			// 获取部门下拉列表
			getDepartmentList(type, CompanyId) {
				DepartmentList({
					DeptId: CompanyId
				}).then(resJson => {
					if (resJson.Success) {
						this.columns = resJson.Data.map(item => {
							return {
								value: item.Id,
								label: item.Name
							}
						})
						console.log('获取部门下拉列表columns', this.columns)
						// /如果是默认过来的
						if (type === '默认') {
							this.entity.DeptName = ""
							this.entity.DepartmentId = ""
							// 部门的名称和id回显
							let DeptName = this.columns.filter(item => item.value === this.UserInfo
								.UserInfo.DepartId)[0].label
							let DepartmentId = this.columns.filter(item => item.value === this.UserInfo
								.UserInfo.DepartId)[0].value
							this.$set(this.entity, 'DeptName', DeptName)
							this.$set(this.entity, 'DepartmentId', DepartmentId)
							// 强制更新
							this.$forceUpdate()
							console.log('获取部门下拉列表数据--默认-------------', this.entity, DeptName)
							return
						} else {
							// 否则走下拉选择逻辑
							this.$refs.Company.open(this.columns)
						}

					}


				})
			},

			// 提交
			onSubmit(type) {
				// 判断报销人姓名是否存在人员档案中  不存在  禁止保存和提交
				Base_UserGetExistEmployee({
					staffName: this.entity.ApplicationPerson
				}).then(resJson => {
					console.log('是否在', resJson)
					if (!resJson.Data) {
						// 说明该报销人姓名存在人员档案中 允许保存和提交
						this.$errorToast(type == 0 ? '报销人不在人员档案中，无法保存' : '报销人不在人员档案中，无法提交')
						return
					}
					// 最终提交
					this.SubmitRequest(type)

				})
				console.log('保存了', type, this.entity)
			},
			// 最终提交
			SubmitRequest(type) {
				// 点击 1.保存草稿  2  提交
				var that = this
				// 点击的是提交
				if (type == 1) {
					this.isButtonDisabled = true
					this.loading = true
					// 点击的是提交   判断子表是否全部为空  禁用
					if (this.detailData.length == 0) {
						setTimeout(function() {
							that.loading = false
							that.isButtonDisabled = false
						}, 1000)
						this.$errorToast('请添加明细后再提交')
						return
					}

				}
				this.$refs.form.validate().then(res => {
					// this.resetFields()
					let newEntity = JSON.parse(JSON.stringify(this.entity))
					let detailData = JSON.parse(JSON.stringify(this.detailData))

					console.log('開始處理', detailData, newEntity)
					// 差额
					newEntity['Difference'] = this.entity.Difference ? this.entity.Difference : 0
					// 票面金额
					newEntity['FaceAmount'] = this.entity.FaceAmount ? this.entity.FaceAmount : 0
					// 应付金额
					newEntity['PayableAmount'] = this.entity.PayableAmount ? this.entity.PayableAmount : 0
					// 报销金额
					newEntity['ReimburseAmount'] = this.entity.ReimburseAmount ? this.entity.ReimburseAmount : 0
					// 提交 1  草稿  0
					newEntity['Satus'] = type
					// 子表明细
					newEntity['reimburse_Daily_ItemDTOs'] = detailData
					newEntity['CreatorId'] = this.UserInfo.UserInfo.CreatorId
					// newEntity['CompanyId'] = this.UserInfo.CompanyId
					newEntity['TemplateId'] = this.options.TemplateId
					// 单独处理附件格式参数
					if (newEntity.reimburse_Daily_ItemDTOs.length > 0) {
						newEntity.reimburse_Daily_ItemDTOs.forEach(item => {
							let Upload = []
							if (item.reimburse_Files && item.reimburse_Files.length > 0) {
								item.reimburse_Files.forEach(v => {
									// 如果是新上传的 直接放到Upload里
									if (v.fileEntity.id && !v.invoiceId) {
										delete v.invoiceId
										Upload.push(v)
									}
								})
								item.reimburse_Files = item.reimburse_Files.map(v => {
									return {
										FilePath: v.fileEntity.linkUrl
									}
								})
							}
							item.Upload = Upload

						})
					}

					// 点击 1.保存草稿  2  提交
					console.log('日常最终最终提交了--------', newEntity)

					this.loading = true
					uni.showLoading({
						title: '加载中'
					})
					Reimburse_Daily_MainSaveData(newEntity)
						.then(resJson => {
							if (resJson.Success) {
								that.$sucessToast('新建成功')
								setTimeout(function() {
									that.loading = false
									uni.navigateBack()
									uni.hideLoading()

								}, 2500)
							} else {
								that.$errorToast(resJson.Msg);
								setTimeout(function() {
									that.loading = false
									uni.navigateBack()
									uni.hideLoading()
								}, 2500)
							}
						});

				}).catch(err => {
					uni.hideLoading()
					that.loading = false
				})


			}

		}
	}
</script>

<style lang="less" scoped>
	// 覆盖uni-section 的样式uni-section
	::v-deep.uni-section {
		.uni-section-header {
			padding: 24rpx 0 !important;
		}
	}

	/* 设置 label 的样式 */
	::v-deep.uni-forms-item {
		padding-right: 40rpx !important;

		/* 例如，设置 label 的宽度和对齐方式 */
		.uni-forms-item__label {
			display: flex !important;
			justify-content: flex-end !important;
		}
	}

	.container {
		.scrollBox {

			margin-bottom: 130rpx;
			/* #ifdef H5 */
			height: calc(100vh - 360px);
			/* #endif */
			/* #ifdef APP */
			height: calc(100vh - 220px);
			/* #endif */
		}

		/* 适配底部导航栏 */
		.submitButton {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			height: 100rpx;
			/*暂时发现安卓小屏手机安全区为0 && 不带单位的话padding-bottom会失效，写一个兜底, 并写在最上面；f12发现css样式如果都给height设置样式，会依次往下，用最底下的一个样式，如果最下面的没失效，依次往上查找，所以兜底的写在最上面 */
			height: calc(130rpx + constant(safe-area-inset-bottom));
			/* 直接扩展高度，因为padding-bottom是内边距 */
			height: calc(130rpx + env(safe-area-inset-bottom));
			/* 直接扩展高度 */
			background: #fff;
			padding-top: 10rpx;
			box-sizing: border-box;
			padding-bottom: constant(safe-area-inset-bottom);
			/*兼容 iOS<11.2 */
			padding-bottom: env(safe-area-inset-bottom);
			/* 兼容iOS>= 11.2*/
			border-top: 1px solid #e9e9e9;
			padding-left: 15px;
			padding-right: 15px;
		}
	}
</style>